package ggze.esp.service.impl;

import ggze.esp.dao.inter.*;
import ggze.esp.entity.FspDataRecord;
import ggze.esp.entity.FspDictionary;
import ggze.esp.entity.FspLookRecord;
import ggze.esp.entity.FspUser;
import ggze.esp.service.CommonService;
import ggze.tool.JwtToken;
import ggze.tool.ReturnBody;
import ggze.tool.SystemUtils;
import ggze.tool.TimeUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CommonServiceImpl implements CommonService {
    @Autowired
    private FspDictionaryDao fspDictionaryDao;
    @Autowired
    private FspDataRecordDao fspDataRecordDao;
    @Autowired
    private FspLookRecordDao fspLookRecordDao;
    @Autowired
    private MPSDao mpsDao;
    @Autowired
    private FspUserDao fspUserDao;

    @Override
    public Map<String, String> getArrayMap(Map<String, String> map, String[] array) {
        Map<String,String> linkedMap = new LinkedHashMap<String, String>();
        for(int i=0;i<array.length;i++){
            linkedMap.put(array[i],map.get(array[i]));
        }
        return linkedMap;
    }

    @Override
    public ReturnBody chaekUser(String tooken,String apiID,String type,HttpServletRequest request) throws Exception{
        ReturnBody returnBody = new ReturnBody();

        //当前API或试图是否开启权限验证
        if(type.equals("api")){
            FspDataRecord fspDataRecord = fspDataRecordDao.isSelect("uuid",apiID);
            if(fspDataRecord.getF_IS_ROLE().equals("0")){
                returnBody.setCode("0");
                return  returnBody;
            }
        }
        if(type.equals("look")){
            FspLookRecord fspLookRecord = fspLookRecordDao.isSelect("uuid",apiID);
            if(fspLookRecord.getF_IS_ROLE().equals("0")){
                returnBody.setCode("0");
                return returnBody;
            }
        }
        if(JwtToken.verifyToken(tooken)==null&&tooken==null){
            returnBody.setCode("0");
            return returnBody;
        }
        String viftoken = JwtToken.verifyToken(tooken).get("content").asString();
        JSONObject tokenJSON = JSONObject.fromObject(viftoken);
        //用户ID
        String uuid = tokenJSON.getString("uuid");
        String ip = tokenJSON.getString("ip");
        String time = tokenJSON.getString("time");
        //用户被禁用
        FspUser fspUser = fspUserDao.isSelect("uuid",uuid);
        if(fspUser.getF_STATUS().equals("1")){
            returnBody.setCode("1");
            returnBody.setTitle("用户被禁用！");
            return returnBody;
        }
        //是否超时
        FspDictionary ck = fspDictionaryDao.isSelect("uuid","1555508458589");
        //分钟，小时，天
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = df.parse(TimeUtils.getTimeFormat());
        Date d2 = df.parse(time);
        long diff = d1.getTime() - d2.getTime();
        switch (ck.getF_DICTIONARY_STYLE()){
            case "day":{
                long days = diff / (1000 * 60 * 60 * 24);
                if(days>=Long.parseLong(ck.getF_DICTIONARY_VAL())){
                    returnBody.setCode("1");
                    returnBody.setTitle("token超时；重新登录！");
                    return returnBody;
                }
            };break;
            case "minutes":{
                long minutes = diff / (1000 * 60);
                if(minutes>=Long.parseLong(ck.getF_DICTIONARY_VAL())){
                    returnBody.setCode("1");
                    returnBody.setTitle("token超时；重新登录！");
                    return returnBody;
                }
            };break;
            case "hours":{
                long hours = diff / (1000 * 60 * 60);
                if(hours>=Long.parseLong(ck.getF_DICTIONARY_VAL())){
                    returnBody.setCode("1");
                    returnBody.setTitle("token超时；重新登录！");
                    return returnBody;
                }
            };break;
        }
        //当前用户是否有权限
        StringBuilder sql = new StringBuilder();
        if(type.equals("api")){
            sql.setLength(0);
            sql.append("select * from fsp_role_data as b LEFT join fsp_user as c on c.F_STATE = b.F_ROLE_CODE where b.F_DATA_ID='"+apiID+"' and c.UUID='"+uuid+"'");
            List<Map<String, String>> dataleng = mpsDao.commonSql(sql.toString());
            if(dataleng.size()<=0){
                returnBody.setCode("1");
                return  returnBody;
            }
        }
        if(type.equals("look")){
            sql.setLength(0);
            sql.append("select * from fsp_role_look as b LEFT join fsp_user as c on c.F_STATE = b.F_ROLE_CODE where b.F_LOOK_ID='"+apiID+"' and c.UUID='"+uuid+"'");
            List<Map<String, String>> lookleng = mpsDao.commonSql(sql.toString());
            if(lookleng.size()<=0){
                returnBody.setCode("1");
                return  returnBody;
            }
        }
        /*//当前登录ip是否和token不一
        if(!ip.equals(SystemUtils.getIpAddr(request))){
            returnBody.setCode("1");
            returnBody.setTitle("token鉴权失败！请重新登录！");
            return returnBody;
        }*/
        returnBody.setCode("0");
        return returnBody;
    }
}
